﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.SlaughterCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.SlaughterCommandHandler
{
    public class SlaughterAddCommandHandler : IRequestHandler<SlaughterAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Slaughter_Information> _slaughterRepository;
        private readonly IMapper mapper;

        public SlaughterAddCommandHandler(IBaseRepository<Slaughter_Information> slaughterRepository, IMapper mapper)
        {
            _slaughterRepository = slaughterRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(SlaughterAddCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<Slaughter_Information>(request);
            if(request.Id!=0)
            {
                model.UpDataUserId = request.CreateUserId;
                model.UpDataTime=DateTime.Now;
            }

            int count=await _slaughterRepository.Update(model);

            APIResult<int> aPIResult = new APIResult<int>();
            if (count > 0)
            {
                aPIResult.Code = EnumCode.Ok;
                aPIResult.Data = count;
                aPIResult.Msg = "保存成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = count;
                aPIResult.Msg = "保存失败";
            }
            return await Task.FromResult(aPIResult);
        }
    }
}
